<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Common\ApiResponse;

class CheckHeaderReplaceId
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($headerParkingLotID = request()->header('Parking-Lot-Id')) {
            $user = admin();
            $scopeParkingLotIDs = optional($user)->parkingLotIDs ?: [];
            if (in_array($headerParkingLotID, $scopeParkingLotIDs, true)) {
                app()->instance('parking_lot_id', $headerParkingLotID);
            } else {
                throw new \InvalidArgumentException('不能确定当前车场数据!', ApiResponse::CODE_HEADER_ERR);
            }
        } else {
            throw new \InvalidArgumentException('车场ID为空!', ApiResponse::CODE_HEADER_ERR);
        }
        return $next($request);
    }
}
